﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ControlsLib;
using GestionePolveri2.Filters;
using GestionePolveriLib.BL.FilterBags;
using BrightIdeasSoftware;
using GestionePolveriLib.Facades.Reports;
using FrameworkLib.Utilities.Export;
using FrameworkLib.Configurations.FormsConfiguration;
using GestionePolveriLib.BL;
using GestionePolveriLib.BL.Reports;
using FrameworkLib.Utilities.Sorting;
using FrameworkLib.Configurations.FormsConfiguration.BL;

namespace GestionePolveri2
{
    public partial class ReportDirezionaleForm : ReportDirezionaleBase
    {
        Color rigaTotali = Color.FromArgb(255, 246, 143);

        string[] columnsToHide = null;
        OLVColumn sortColumn = null;
        SortOrder m_sortOrder = SortOrder.Ascending;
        SplashPage sp = null;
        GestionePolveriLib.BL.Reports.ReportDirezionale rdTotali = null;
        //TotalViewerDialog m_tvd = null;
        TotaliValori m_totVal = null;

        public ReportDirezionaleForm()
        {
            SetupColumns();

            InitializeComponent();
        }

        public override void InitializeForm()
        {
            System.Security.Principal.IPrincipal m_operatore = System.Threading.Thread.CurrentPrincipal;
            string[] roles = System.Web.Security.Roles.GetRolesForUser(m_operatore.Identity.Name);

            SavingConfigurationBag scb = new SavingConfigurationBag();
            scb.FormName = this.Name;
            scb.RoleName = roles[0];
            this.SavingConfigurationBag = scb;

            base.InitializeForm();

            this.ShowCNFGMenu = true;

            this.AddCustomButton("btnEsportaToExcel", "Esporta in Excel");
            this.AddCustomButton("btnShowTotals", "Mostra Totali");
            //this.AddCustomButton("btnShowTotals", "Mostra Totali");

            this.CanModify = false;
            this.ShowOnlyCustomButton = true;

            this.ItemSelected += new EventHandler<CustomEventArgs<GestionePolveriLib.BL.Reports.ReportDirezionale>>(Anagrafica_ItemSelected);

            this.objectListView1.OwnerDraw = true;
            this.objectListView1.OwnerDrawnHeader = true;
            //this.objectListView1.ItemChecked += new ItemCheckedEventHandler(objectListView1_ItemChecked);
            this.objectListView1.FormatCell += new EventHandler<FormatCellEventArgs>(objectListView1_FormatCell);
            //this.objectListView1.CellClick += new EventHandler<CellClickEventArgs>(objectListView1_CellClick); 

            this.objectListView1.UseCellFormatEvents = true;
            
            NascondiColonne();

            this.splitContainer3.Visible = true;
            this.label1.Visible = false;
            this.label2.Visible = false;
            this.label3.Visible = false;
        }

        protected override void OnLoadCompleted()
        {
            base.OnLoadCompleted();

            this.objectListView1.GridLines = true;
            this.objectListView1.ShowGroups = false;

            this.IsFiltering = true;
            this.Filter.FilterBag.Ordinamento = 2;

            this.ManageData();
        }

        //public override void OnSalvaConfigurazioneMaschera()
        //{
        //    base.OnSalvaConfigurazioneMaschera();

        //    byte[] data = this.objectListView1.SaveState();

        //    ColumnsConfigurationManager ccm = new ColumnsConfigurationManager();
        //    ccm.FormName = this.Name;
        //    ccm.State = data;
        //    ccm.SaveState();
        //}

        //public override void OnRipristinaConfigurazioneDefaultMascheraClicked()
        //{
        //    base.OnRipristinaConfigurazioneDefaultMascheraClicked();
        //}

        private void objectListView1_FormatCell(object sender, FormatCellEventArgs e)
        {
            ReportDirezionale mov = (ReportDirezionale)e.Model;
            //Color m_color = Color.White;

            if (mov.Tag == "RigaTotali")
            {
                e.Item.BackColor = rigaTotali;
                e.SubItem.BackColor = rigaTotali;
            }
        }

        private void SetupColumns()
        {
            this.objectListView1.SuspendLayout();

            CreateColumn("Famiglia", "Famiglia", 69, "");
            CreateColumn("ColoriAbbinati", "Colori Abbinati", 69, "");
            CreateColumn("Applicazione", "Tipo", 69, "");
            CreateColumn("CodicePolvere", "Codice Polvere", 69, "");
            CreateColumn("Note", "Note Polvere", 69, "");
            CreateColumn("Descrizione", "Descrizione", 69, "");
            CreateColumn("Fornitore", "Fornitore", 69, "");
            CreateColumn("ScortaMinima", "Scorta Minima", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("Codice", "Tipol. Scorta min.", 69, "");
            CreateColumn("PrezzoUnitario", "Ultimo Prezzo", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("Giacenza", "Carico-Scarico [Kg]", 80, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("GiacenzaXValore", "Valore €", 69, "{0:C}", HorizontalAlignment.Right);
            CreateColumn("Carico", "Carico [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("Scarico", "Scarico [Kg]", 75, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("ValoreXScarico", "Valor. Scarico.", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NumeroPrelievi", "Numero Prelievi", 69, "{0:d}", HorizontalAlignment.Right);

            //
            CreateColumn("Giacenza_Att", "Giacenza Att.", 80, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("GiacenzaAttualeValore", "Valore Giacenza Att.", 80, "{0:N}", HorizontalAlignment.Right);

            //
            CreateColumn("Cons_RAL1", "RAL1 [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_RAL1", "RAL1 Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_RAL2", "RAL2 [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_RAL2", "RAL2 Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_Verticale", "Verticale [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_Verticale", "Verticale Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_Sublimato", "Sublimato [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_Sublimato", "Sublimato Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_Ferro", "Ferro [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_Ferro", "Ferro Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_ColorwoodGrande", "Colorwood Grande [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_ColorwoodGrande", "Colorwood Grande Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_ColorwoodPiccolo", "Colorwood Piccolo [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_ColorwoodPiccolo", "Colorwood Piccolo Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_Reso", "Reso [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_Reso", "Reso Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_Smaltito", "Smaltito [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_Smaltito", "Smaltito Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_Venduto", "Venduto [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_Venduto", "Venduto Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_Correzione", "Inventario [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_Correzione", "Inventario Np.", 69, "{0:D}", HorizontalAlignment.Right);
            CreateColumn("Cons_AllineamentoInventario", "Allineamento Inventario [Kg]", 69, "{0:N}", HorizontalAlignment.Right);
            CreateColumn("NP_AllineamentoInventario", "Allineamento Inventario Np.", 69, "{0:D}", HorizontalAlignment.Right);

            this.objectListView1.ResumeLayout();
        }

        private void CreateColumn(string propertyName, string text, int width, string format)
        {
            BrightIdeasSoftware.OLVColumn olvColumn = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
            
            objectListView1.AllColumns.Add(olvColumn);

            objectListView1.Columns.Add((System.Windows.Forms.ColumnHeader)olvColumn);

            olvColumn.AspectName = propertyName;
            olvColumn.AspectToStringFormat = (!string.IsNullOrWhiteSpace(format) ? format : string.Empty);
            olvColumn.Text = text;
            olvColumn.Width = width;
            olvColumn.TextAlign = HorizontalAlignment.Left;
        }

        private void CreateHiddenColumn(string propertyName)
        {
            BrightIdeasSoftware.OLVColumn olvColumn = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));

            objectListView1.AllColumns.Add(olvColumn);

            objectListView1.Columns.Add((System.Windows.Forms.ColumnHeader)olvColumn);

            olvColumn.AspectName = propertyName;
            olvColumn.Text = propertyName;
            olvColumn.IsVisible = true;
            olvColumn.Width = 0;
        }

        private void CreateColumn(string propertyName, string text, int width, string format, HorizontalAlignment alignment)
        {
            BrightIdeasSoftware.OLVColumn olvColumn = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));

            objectListView1.AllColumns.Add(olvColumn);

            objectListView1.Columns.Add((System.Windows.Forms.ColumnHeader)olvColumn);

            olvColumn.AspectName = propertyName;
            olvColumn.AspectToStringFormat = (!string.IsNullOrWhiteSpace(format) ? format : string.Empty);
            olvColumn.Text = text;
            olvColumn.Width = width;
            olvColumn.TextAlign = alignment;
        }

        protected override void OnButtonsBarClicked(CustomEventArgs<GestionePolveriLib.BL.Reports.ReportDirezionale> e)
        {
            base.OnButtonsBarClicked(e);
        }

        protected override void OnCustomButtonsBarClicked(CustomEventArgs<GestionePolveriLib.BL.Reports.ReportDirezionale> e)
        {
            base.OnCustomButtonsBarClicked(e);

            //if (e.ButtonName.Equals("btnShowTotals", StringComparison.InvariantCultureIgnoreCase))
            //{
            //    m_tvd = new TotalViewerDialog();

            //    CalcolaTotali((List<GestionePolveriLib.BL.Reports.ReportDirezionale>)this.objectListView1.Objects);

            //    m_tvd.TotalsContainer = rdTotali;

            //    // qui si nascondono le colonne da non visualizzare in base al ruolo...
            //    if (columnsToHide != null)
            //    {
            //        foreach (string s in columnsToHide)
            //        {
            //            m_tvd.ShowTotalElement(s, false);
            //        }
            //    }

            //    // qui si nascondono le colonne da non visualizzare perchè nascoste da configurazione...
            //    this.objectListView1.AllColumns.ForEach(x => m_tvd.ShowTotalElement(x.AspectName, x.IsVisible));
                
            //    //foreach (OLVColumn c in this.objectListView1.AllColumns)
            //    //{
            //    //    m_tvd.ShowTotalElement(c.AspectName, c.IsVisible);
            //    //}

            //    m_tvd.Show(this);
            //}

            if (e.ButtonName.Equals("btnShowTotals", StringComparison.InvariantCultureIgnoreCase))
            {
                this.splitContainer1.Panel2Collapsed = !this.splitContainer1.Panel2Collapsed;
            }

            if (e.ButtonName.Equals("btnEsportaToExcel", StringComparison.InvariantCultureIgnoreCase))
            {
                List<ReportDirezionale> result = null;

                if (sortColumn != null)
                {
                    bool sortOrder = (m_sortOrder == SortOrder.Ascending ? true : false);
                    IOrderedEnumerable<ReportDirezionale> result2 = ((List<ReportDirezionale>)this.objectListView1.Objects).OrderBy(sortColumn.AspectName, sortOrder);

                    result = result2.ToList();
                }
                else
                {
                    result = (List<ReportDirezionale>)this.objectListView1.Objects;
                }

                ReportDirezionaleFacade rdf = new ReportDirezionaleFacade(this.Filter.FilterBag);
                //rdf.RunAsync(() => rdf.GetReportData(), (result) =>
                //{
                    if (result != null)
                    {
                        OperatorePrincipal m_OperatorePrincipale = (OperatorePrincipal)System.Threading.Thread.CurrentPrincipal;
                        if ((!m_OperatorePrincipale.IsInRole("Amministrazione")) && (!m_OperatorePrincipale.IsInRole("Direzione")))
                        {
                            columnsToHide = new string[] { 
                                        "Cons_RAL1", "NP_RAL1", 
                                        "Cons_RAL2", "NP_RAL2", 
                                        "Cons_Verticale", "NP_Verticale", 
                                        "Cons_Ferro", "NP_Ferro", 
                                        "Cons_ColorwoodGrande", "NP_ColorwoodGrande", 
                                        "Cons_ColorwoodPiccolo", "NP_ColorwoodPiccolo",
                                        "Cons_Reso", "NP_Reso", 
                                        "Cons_Smaltito", "NP_Smaltito", 
                                        "Cons_Venduto", "NP_Venduto",
                                        "Cons_Correzione", "NP_Correzione",
                                        "Cons_AllineamentoInventario", "NP_AllineamentoInventatio"
                            };
                        }

                        //string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        //string filename = string.Format(@"{0}\Prova.xls", path);

                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Filter = "Excel Files (.xls)|*.xls|All Files (*.*)|*.*";
                        sfd.FilterIndex = 1;
                        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            string errorMessage = string.Empty;
                            if (result.ToExcel(sfd.FileName, out errorMessage, columnsToHide))
                            {
                                MessageBox.Show("Esportazione in Excel effettuata!", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                MessageBox.Show(string.Format("ATTENZIONE: Si è verificato un errore: {0}", errorMessage), "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Nessun dato da inviare in stampa.", "Gestione Polveri", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                //});
            }
        }

        void Anagrafica_ItemSelected(object sender, CustomEventArgs<GestionePolveriLib.BL.Reports.ReportDirezionale> e)
        {
            base.Current = e.Item;
        }

        void Anagrafica_CustomButtonClicked(object sender, CustomEventArgs<GestionePolveriLib.BL.Reports.ReportDirezionale> e)
        {

        }

        public override void OnFilterExecuted()
        {
            base.OnFilterExecuted();

            this.objectListView1.Sorting = SortOrder.None;
            this.objectListView1.Unsort();

            this.IsFiltering = true;

            ManageData();
        }

        public override void OnFilterReset()
        {
            base.OnFilterReset();

            this.objectListView1.Sorting = SortOrder.None;
            this.objectListView1.Unsort();

            this.IsFiltering = true;
            this.Filter.FilterBag.Ordinamento = 2;

            ManageData();
        }

        public override void OnRefreshFilterData()
        {
            base.OnRefreshFilterData();

            this.objectListView1.Unsort();

            ManageData();
        }

        protected override void LoadData()
        {
            base.LoadData();

            ReportDirezionaleFacade rdf = new ReportDirezionaleFacade();
            rdf.RunAsync(() => rdf.GetReportData(), (result) =>
            {
                if (result != null)
                {
                    this.objectListView1.SetObjects((List<GestionePolveriLib.BL.Reports.ReportDirezionale>)result, true);
                    this.objectListView1.Refresh();
                }
            });
        }

        protected override void LoadData(ReportDirezionaleFilterBag filter)
        {
            sp = new SplashPage();
            sp.ShowDialog();

            base.LoadData(filter);

            ReportDirezionaleFacade rdf = new ReportDirezionaleFacade(filter);
            rdf.RunAsync(() => rdf.GetReportData(), (result) =>
            {
                if (result != null)
                {
                    result = CalcolaTotali((List<GestionePolveriLib.BL.Reports.ReportDirezionale>)result);

                    this.objectListView1.SetObjects((List<GestionePolveriLib.BL.Reports.ReportDirezionale>)result, true);
                    this.objectListView1.Refresh();

                    sp.Close();
                }
            });
        }

        private List<GestionePolveriLib.BL.Reports.ReportDirezionale> CalcolaTotali(List<GestionePolveriLib.BL.Reports.ReportDirezionale> items)
        {
            rdTotali = new GestionePolveriLib.BL.Reports.ReportDirezionale();
            rdTotali.Tag = "RigaTotali";

            int NP_RAL1 = 0;
            int NP_RAL2 = 0; 
            int NP_Reso  = 0;
            int NP_Smaltito = 0;
            int NP_Sublimato = 0;
            int NP_Venduto  = 0;
            int NP_Verticale  = 0;
            int NP_Ferro  = 0;
            int NP_Correzione  = 0;
            int NP_ColorwoodPiccolo = 0;
            int NP_ColorwoodGrande  = 0;
            int NP_AllineamentoInventatio = 0;
            
            double m_carico = 0;
            double m_scarico = 0;
            double m_scortaMinima = 0;
            double m_giacenza = 0;
            double m_giacenza_att = 0;
            double m_giacenza_att_valore = 0;
            double m_giacenzaXValore = 0;
            double m_valoreXScarico = 0;

            double m_consAllineamentoInventario = 0;
            double m_consColorwoodGrande = 0;
            double m_consColorwoodPiccolo = 0;
            double m_consCorrezione = 0;
            double m_consFerro = 0;
            double m_consRAL1 = 0;
            double m_consRAL2 = 0;
            double m_consReso = 0;
            double m_consSmaltito = 0;
            double m_consSublimato = 0;
            double m_consVenduto = 0;
            double m_consVerticale = 0;

            m_totVal = new TotaliValori();
            
            foreach (GestionePolveriLib.BL.Reports.ReportDirezionale item in items)
            {
                rdTotali.NumeroPrelieviTot += item.NumeroPrelievi;

                NP_RAL1 += item.NP_RAL1;
                NP_RAL2 += item.NP_RAL2;
                NP_Reso += item.NP_Reso;
                NP_Smaltito += item.NP_Smaltito;
                NP_Sublimato += item.NP_Sublimato;
                NP_Venduto += item.NP_Venduto;
                NP_Verticale += item.NP_Verticale;
                NP_Ferro += item.NP_Ferro;
                NP_Correzione += item.NP_Correzione;
                NP_ColorwoodPiccolo += item.NP_ColorwoodPiccolo;
                NP_ColorwoodGrande += item.NP_ColorwoodGrande;
                NP_AllineamentoInventatio += item.NP_AllineamentoInventario;

                m_carico += item.Carico;
                m_scarico += item.Scarico;
                m_giacenza += item.Giacenza;
                m_giacenza_att += item.Giacenza_Att;
                m_giacenza_att_valore += item.GiacenzaAttualeValore.GetValueOrDefault(0);

                m_giacenzaXValore += item.GiacenzaXValore.GetValueOrDefault(0);

                m_consAllineamentoInventario += item.Cons_AllineamentoInventario;
                m_consColorwoodGrande += item.Cons_ColorwoodGrande;
                m_consColorwoodPiccolo += item.Cons_ColorwoodPiccolo;
                m_consCorrezione += item.Cons_Correzione;
                m_consFerro += item.Cons_Ferro;
                m_consRAL1 += item.Cons_RAL1;
                m_consRAL2 += item.Cons_RAL2;
                m_consReso += item.Cons_Reso;
                m_consSmaltito += item.Cons_Smaltito;
                m_consSublimato += item.Cons_Sublimato;
                m_consVenduto += item.Cons_Venduto;
                m_consVerticale += item.Cons_Verticale;

                m_scortaMinima += item.ScortaMinima;

                m_valoreXScarico += item.ValoreXScarico.GetValueOrDefault(0);


                m_totVal.ValAllineamentoInventario += item.VAL_AllineamentoInventario;
                m_totVal.ValColorwoodGrande += item.VAL_ColorwoodGrande;
                m_totVal.ValColorwoodPiccolo += item.VAL_ColorwoodPiccolo;
                m_totVal.ValCorrezione += item.VAL_Correzione;
                m_totVal.ValFerro += item.VAL_Ferro;
                m_totVal.ValRAL1 += item.VAL_RAL1;
                m_totVal.ValRAL2 += item.VAL_RAL2;
                m_totVal.ValReso += item.VAL_Reso;
                m_totVal.ValSmaltito += item.VAL_Smaltito;
                m_totVal.ValSublimato += item.VAL_Sublimato;
                m_totVal.ValVenduto += item.VAL_Venduto;
                m_totVal.ValVerticale += item.VAL_Verticale;
                

                //rd.NP_RAL1 += (item.NP_RAL1 == null ? (int?)0 : (int?)item.NP_RAL1);
                //rd.NP_RAL2 += (item.NP_RAL2 == null ? (int?)0 : (int?)item.NP_RAL2);
                //rd.NP_Reso += (item.NP_Reso == null ? (int?)0 : (int?)item.NP_Reso);
                //rd.NP_Smaltito += (item.NP_Smaltito == null ? (int?)0 : (int?)item.NP_Smaltito);
                //rd.NP_Sublimato += (item.NP_Sublimato == null ? (int?)0 : (int?)item.NP_Sublimato);
                //rd.NP_Venduto += (item.NP_Venduto == null ? (int?)0 : (int?)item.NP_Venduto);
                //rd.NP_Verticale += (item.NP_Verticale == null ? (int?)0 : (int?)item.NP_Verticale);
                //rd.NP_Ferro += (item.NP_Ferro == null ? (int?)0 : (int?)item.NP_Ferro);
                //rd.NP_Correzione += (item.NP_Correzione == null ? (int?)0 : (int?)item.NP_Correzione);
                //rd.NP_ColorwoodPiccolo += (item.NP_ColorwoodPiccolo == null ? (int?)0 : (int?)item.NP_ColorwoodPiccolo);
                //rd.NP_ColorwoodGrande += (item.NP_ColorwoodGrande == null ? (int?)0 : (int?)item.NP_ColorwoodGrande);
                //rd.NP_AllineamentoInventatio += (item.NP_AllineamentoInventatio == null ? (int?)0 : (int?)item.NP_AllineamentoInventatio);
            }

            rdTotali.NP_RAL1 = NP_RAL1;
            rdTotali.NP_RAL2 = NP_RAL2;
            rdTotali.NP_Reso = NP_Reso;
            rdTotali.NP_Smaltito = NP_Smaltito;
            rdTotali.NP_Sublimato = NP_Sublimato;
            rdTotali.NP_Venduto = NP_Venduto;
            rdTotali.NP_Verticale = NP_Verticale;
            rdTotali.NP_Ferro = NP_Ferro;
            rdTotali.NP_Correzione = NP_Correzione;
            rdTotali.NP_ColorwoodPiccolo = NP_ColorwoodPiccolo;
            rdTotali.NP_ColorwoodGrande = NP_ColorwoodGrande;
            rdTotali.NP_AllineamentoInventario = NP_AllineamentoInventatio;

            rdTotali.Cons_Verticale = m_consVerticale;
            rdTotali.Cons_Venduto = m_consVenduto;
            rdTotali.Cons_Sublimato = m_consSublimato;
            rdTotali.Cons_Smaltito = m_consSmaltito;
            rdTotali.Cons_Reso = m_consReso;
            rdTotali.Cons_RAL2 = m_consRAL2;
            rdTotali.Cons_RAL1 = m_consRAL1;
            rdTotali.Cons_Ferro = m_consFerro;
            rdTotali.Cons_Correzione = m_consCorrezione;
            rdTotali.Cons_ColorwoodPiccolo = m_consColorwoodPiccolo;
            rdTotali.Cons_ColorwoodGrande = m_consColorwoodGrande;
            rdTotali.Cons_AllineamentoInventario = m_consAllineamentoInventario;

            rdTotali.Carico = m_carico;
            rdTotali.Scarico = m_scarico;
            rdTotali.ScortaMinima = m_scortaMinima;
            rdTotali.Giacenza = m_giacenza;
            rdTotali.Giacenza_Att = m_giacenza_att;
            rdTotali.GiacenzaAttualeValore = m_giacenza_att_valore;

            rdTotali.UseCalculatedField = false;
            rdTotali.GiacenzaXValore = m_giacenzaXValore;
            rdTotali.ValoreXScarico = m_valoreXScarico;

            items.Insert(0, rdTotali);

            PrintTotali(rdTotali);

            return items;
        }

        private void PrintTotali(ReportDirezionale rdTotali)
        {
            this.label1.Text = string.Format("Giacenza: {0:N} Kg., Valore Giacenza: {1:N} €, Tot. Carico: {2:N} Kg.,  Tot. Scarico: {3:N} Kg., Valoriz. Scarico: {4:N} €", 
                                                   rdTotali.Giacenza, rdTotali.GiacenzaXValore, rdTotali.Carico, rdTotali.Scarico, rdTotali.ValoreXScarico);

            this.label2.Text = string.Format("Ral1: {0:N} Kg. / {1} / {2:C}, Ral2: {3:N} Kg. / {4} / {5:C}, Vert.: {6:N} Kg. / {7} / {8:C}, Sublim.: {9:N} Kg. / {10}, {11:C}, Ferro: {12:N} Kg. / {13} / {14:C}, Colorwood Grande: {15:N} Kg. / {16} / {17:C}, Colorwood Piccolo: {18:N} Kg. / {19} / {20:C}", 
                                                  rdTotali.Cons_RAL1, rdTotali.NP_RAL1, rdTotali.VAL_RAL1, 
                                                  rdTotali.Cons_RAL2, rdTotali.NP_RAL2, rdTotali.VAL_RAL2,
                                                  rdTotali.Cons_Verticale, rdTotali.NP_Verticale, rdTotali.VAL_Verticale,
                                                  rdTotali.Cons_Sublimato, rdTotali.NP_Sublimato, rdTotali.VAL_Sublimato,
                                                  rdTotali.Cons_Ferro, rdTotali.NP_Ferro, rdTotali.VAL_Ferro,
                                                  rdTotali.Cons_ColorwoodGrande, rdTotali.NP_ColorwoodGrande, rdTotali.VAL_ColorwoodGrande, 
                                                  rdTotali.Cons_ColorwoodPiccolo, rdTotali.NP_ColorwoodPiccolo, rdTotali.VAL_ColorwoodPiccolo);

            this.label3.Text = string.Format("Reso: {0:N} / {1} / {2:C}, Smaltito: {3:N} / {4} / {5:C}, Venduto: {6:N} / {7} / {8:C}, Inventario: {9:N} / {10} / {11:C}, Allineamento inv.: {12:N} / {13} / {14:C}",
                                             rdTotali.Cons_Reso, rdTotali.NP_Reso, rdTotali.VAL_Reso,
                                             rdTotali.Cons_Smaltito, rdTotali.NP_Smaltito, rdTotali.VAL_Smaltito,
                                             rdTotali.Cons_Venduto, rdTotali.NP_Venduto, rdTotali.VAL_Venduto,
                                             rdTotali.Cons_Correzione, rdTotali.NP_Correzione, rdTotali.VAL_Correzione,
                                             rdTotali.Cons_AllineamentoInventario, rdTotali.NP_AllineamentoInventario, rdTotali.VAL_AllineamentoInventario);

            this.label1.Visible = this.label2.Visible = this.label3.Visible = false;

            this.lvwTotals.Items.Clear();
            this.lvwTotals2.Items.Clear();

            CreateItemUpper(rdTotali.Giacenza, rdTotali.GiacenzaXValore, rdTotali.Carico, rdTotali.Scarico, rdTotali.ValoreXScarico, rdTotali.NumeroPrelieviTot);

            CreateItem(this.lvwTotals, "RAL1", rdTotali.Cons_RAL1, rdTotali.NP_RAL1, m_totVal.ValRAL1);
            CreateItem(this.lvwTotals, "RAL2", rdTotali.Cons_RAL2, rdTotali.NP_RAL2, m_totVal.ValRAL2);
            CreateItem(this.lvwTotals, "Verticale", rdTotali.Cons_Verticale, rdTotali.NP_Verticale, m_totVal.ValVerticale);
            CreateItem(this.lvwTotals, "Sublimato", rdTotali.Cons_Sublimato, rdTotali.NP_Sublimato, m_totVal.ValSublimato);
            CreateItem(this.lvwTotals, "Ferro", rdTotali.Cons_Ferro, rdTotali.NP_Ferro, m_totVal.ValFerro);
            CreateItem(this.lvwTotals, "Colorwood Grande", rdTotali.Cons_ColorwoodGrande, rdTotali.NP_ColorwoodGrande, m_totVal.ValColorwoodGrande);
            CreateItem(this.lvwTotals2, "Colorwood Piccolo", rdTotali.Cons_ColorwoodPiccolo, rdTotali.NP_ColorwoodPiccolo, m_totVal.ValColorwoodPiccolo);
            CreateItem(this.lvwTotals2, "Reso", rdTotali.Cons_Reso, rdTotali.NP_Reso, m_totVal.ValReso);
            CreateItem(this.lvwTotals2, "Smaltito", rdTotali.Cons_Smaltito, rdTotali.NP_Smaltito, m_totVal.ValSmaltito);
            CreateItem(this.lvwTotals2, "Venduto", rdTotali.Cons_Venduto, rdTotali.NP_Venduto, m_totVal.ValVenduto);
            CreateItem(this.lvwTotals2, "Inventario", rdTotali.Cons_Correzione, rdTotali.NP_Correzione, m_totVal.ValCorrezione);
            CreateItem(this.lvwTotals2, "AllineamentoInventario", rdTotali.Cons_AllineamentoInventario, rdTotali.NP_AllineamentoInventario, m_totVal.ValAllineamentoInventario);            
        }

        private void CreateItemUpper(double? giacenza, double? giacenzaXValore, double? carico, double? scarico, double? valoreXScarico, int numeroPrelievi)
        {
            ListViewItem item = new ListViewItem(string.Format("{0:N}", giacenza));
            ListViewItem.ListViewSubItem item1 = new ListViewItem.ListViewSubItem(item, string.Format("{0:C}", giacenzaXValore));
            ListViewItem.ListViewSubItem item2 = new ListViewItem.ListViewSubItem(item, string.Format("{0:N}", carico));
            ListViewItem.ListViewSubItem item3 = new ListViewItem.ListViewSubItem(item, string.Format("{0:N}", scarico));
            ListViewItem.ListViewSubItem item4 = new ListViewItem.ListViewSubItem(item, string.Format("{0:N}", numeroPrelievi));
            ListViewItem.ListViewSubItem item5 = new ListViewItem.ListViewSubItem(item, string.Format("{0:C}", valoreXScarico));

            item.SubItems.Add(item1);
            item.SubItems.Add(item2);
            item.SubItems.Add(item3);
            item.SubItems.Add(item4);
            item.SubItems.Add(item5);

            this.lvwTotalsUpper.Items.Clear();
            this.lvwTotalsUpper.Items.Add(item);
        }

        private void CreateItemUppers(ListView ctrl, string impianto, double? kg, int? np, double valore)
        {
            ListViewItem item = new ListViewItem(impianto);
            ListViewItem.ListViewSubItem itemKg = new ListViewItem.ListViewSubItem(item, string.Format("{0:N}", kg));
            ListViewItem.ListViewSubItem itemNp = new ListViewItem.ListViewSubItem(item, string.Format("{0}", np));
            ListViewItem.ListViewSubItem itemVal = new ListViewItem.ListViewSubItem(item, string.Format("{0:C}", valore));

            item.SubItems.Add(itemKg);
            item.SubItems.Add(itemNp);
            item.SubItems.Add(itemVal);

            ctrl.Items.Add(item);
        }

        private void CreateItem(ListView ctrl, string impianto, double? kg, int? np, double valore)
        {
            ListViewItem item = new ListViewItem(impianto);
            ListViewItem.ListViewSubItem itemKg = new ListViewItem.ListViewSubItem(item, string.Format("{0:N}", kg));
            ListViewItem.ListViewSubItem itemNp = new ListViewItem.ListViewSubItem(item, string.Format("{0}", np));
            ListViewItem.ListViewSubItem itemVal = new ListViewItem.ListViewSubItem(item, string.Format("{0:C}", valore));

            item.SubItems.Add(itemKg);
            item.SubItems.Add(itemNp);
            item.SubItems.Add(itemVal);

            ctrl.Items.Add(item);
        }

        private void NascondiColonne()
        {
            //this.olvColumnPrezzo.IsVisible = false;
            //this.olvColumnValore.IsVisible = false;

            //OLVColumn c = this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_RAL1"); 

            OperatorePrincipal m_OperatorePrincipale = (OperatorePrincipal)System.Threading.Thread.CurrentPrincipal;
            if ((!m_OperatorePrincipale.IsInRole("Amministrazione")) && (!m_OperatorePrincipale.IsInRole("Direzione")))
            {
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_RAL1"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_RAL1"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_RAL2"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_RAL2"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_Verticale"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_Verticale"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_Ferro"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_Ferro"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_ColorwoodGrande"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_ColorwoodGrande"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_ColorwoodPiccolo"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_ColorwoodPiccolo"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_Reso"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_Reso"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_Smaltito"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_Smaltito"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_Sublimato"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_Sublimato"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_Venduto"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_Venduto"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_Correzione"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_Correzione"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "Cons_AllineamentoInventario"));
                this.objectListView1.AllColumns.Remove(this.objectListView1.AllColumns.First(x => x.AspectName == "NP_AllineamentoInventatio"));

                this.objectListView1.RebuildColumns();

                columnsToHide = new string[] { 
                                        "Cons_RAL1", "NP_RAL1", 
                                        "Cons_RAL2", "NP_RAL2", 
                                        "Cons_Verticale", "NP_Verticale", 
                                        "Cons_Ferro", "NP_Ferro", 
                                        "Cons_ColorwoodGrande", "NP_ColorwoodGrande", 
                                        "Cons_ColorwoodPiccolo", "NP_ColorwoodPiccolo",
                                        "Cons_Reso", "NP_Reso", 
                                        "Cons_Smaltito", "NP_Smaltito", 
                                        "Cons_Sublimato", "NP_Sublimato", 
                                        "Cons_Venduto", "NP_Venduto",
                                        "Cons_Correzione", "NP_Correzione",
                                        "Cons_AllineamentoInventario", "NP_AllineamentoInventatio"
                            };
            }
        }

        public override void OnLoadConfigurazioneMaschera()
        {
            base.OnLoadConfigurazioneMaschera();
        }

        public override void OnRipristinaConfigurazioneDefaultMaschera()
        {
            base.OnRipristinaConfigurazioneDefaultMaschera();
        }

        public override void OnSalvaConfigurazioneMaschera()
        {
            base.OnSalvaConfigurazioneMaschera();

            byte[] data = this.objectListView1.SaveState();

            System.Security.Principal.IPrincipal m_operatore = System.Threading.Thread.CurrentPrincipal;
            string[] roles = System.Web.Security.Roles.GetRolesForUser(m_operatore.Identity.Name);

            SavingConfigurationBag scb = new SavingConfigurationBag();
            scb.FormName = this.Name;
            scb.RoleName = roles[0];
            //scb.UserName = m_operatore.Identity.Name;

            ColumnsConfigurationManager ccm = new ColumnsConfigurationManager();
            ccm.Configuration = scb;
            ccm.State = data;
            ccm.SaveState();
        }
    }

    public class ReportDirezionaleBase : AnagraficaManagerFilteredObjectListView<ReportDirezionale, ReportDirezionaleFilter, ReportDirezionaleFilterBag> { }

    public class TotaliValori
    {
        public double ValAllineamentoInventario { get; set; }
        public double ValColorwoodGrande { get; set; }
        public double ValColorwoodPiccolo { get; set; }
        public double ValCorrezione { get; set; }
        public double ValFerro { get; set; }
        public double ValRAL1 { get; set; }
        public double ValRAL2 { get; set; }
        public double ValReso { get; set; }
        public double ValSmaltito { get; set; }
        public double ValSublimato { get; set; }
        public double ValVenduto { get; set; }
        public double ValVerticale { get; set; }

        public TotaliValori()
        {
            ValAllineamentoInventario = 0;
            ValColorwoodGrande = 0;
            ValColorwoodPiccolo = 0;
            ValCorrezione = 0;
            ValFerro = 0;
            ValRAL1 = 0;
            ValRAL2 = 0;
            ValReso = 0;
            ValSmaltito = 0;
            ValSublimato = 0;
            ValVenduto = 0;
            ValVerticale = 0;
        }
    }
}
